package com.xpmusic.dao.impl;

import com.xpmusic.dao.MusicDAO;
import com.xpmusic.model.MusicInfo;
import com.xpmusic.util.DBUtil;
import org.apache.ibatis.session.SqlSession;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MusicDaoImpl implements MusicDAO {

    /***
     * 获得所有音乐
     * @return
     */
    public List<MusicInfo> getAllMusic() {
        SqlSession sqlSession = DBUtil.openSessionConnection();
        List<MusicInfo> musicInfos = sqlSession.selectList("music.selectMusicInfo");
        sqlSession.close();
        DBUtil.close();
        return musicInfos;
    }

    /***
     * 上传添加音乐
     * @param musicInfo
     * @return
     */
    public boolean uploadMusic(MusicInfo musicInfo) {
        boolean flag = false;
        SqlSession sqlSession = DBUtil.openSessionConnection();
        int i = sqlSession.insert("music.uploadMusic", musicInfo);
        sqlSession.commit();
        flag = i >= 0 ;
        return flag;
    }
    
    
    public void updateMusic(String path) {
        List<MusicInfo> oldList=getAllMusic();//旧的音乐列表
        List<String> pathList=new ArrayList<>();
        File fList[] = new File(path).listFiles();
        for (File file : fList) {
            pathList.add(file.getPath());
        }
        System.out.println("path:"+path+"\r\n" +
                "pathList:"+pathList);
        for (String s : pathList) {
            Pattern p=Pattern.compile("(?<=music.).+(?=.mp3)");//验证文件名是否合法
            Matcher m=p.matcher(s);
            String name;
            if (m.find()){
                name=m.group();
                MusicInfo music=new MusicInfo(name,"./music/"+name+".mp3");
                if (oldList.contains(music)){
                    continue;//如果旧的音乐列表已有此音乐对象，跳过
                }
                SqlSession sqlSession= DBUtil.openSessionConnection();
                try {
                    sqlSession.insert("insert_one",music);
                }catch (RuntimeException e){
                    System.out.println(false);
                }
                sqlSession.commit();
                sqlSession.close();
        
            }
        }
    }
}
